import React, { Component } from "react";
import Form from "./Form";
import List from "./List";

class App extends Component {
  state = {
    list: [
      {
        id: 1,
        name: "tom",
        checked: true,
      },
      {
        id: 2,
        name: "jerry",
        checked: false,
      },
    ],
    flag: false,
  };
  getItem = (value) => {
    // console.log("getItem", value);
    this.state.list.push({
      id: new Date().getTime(),
      name: value,
      checked: false,
    });
    this.setState({});
  };
  remove = (id) => {
    // console.log(id);
    this.setState((prevState) => {
      return {
        list: prevState.list.filter((item) => item.id !== id),
      };
    });
  };

  changeCheck = (id, e) => {
    // console.log("changeCheck", id, e.target.checked);
    const newList = this.state.list.map((item) => {
      if (item.id === id) {
        return {
          ...item,
          checked: e.target.checked,
        };
      } else {
        return item;
      }
    });
    this.setState({
      list: newList,
    });
  };

  removeAll = () => {
    this.setState((prevState) => {
      return {
        list: prevState.list.filter((item) => !item.checked),
      };
    });
  };

  checkAll = () => {
    this.setState((prevState) => {
      return {
        list: prevState.list.map((item) => {
          return {
            ...item,
            checked: !prevState.flag,
          };
        }),
        flag: !prevState.flag,
      };
    });
  };

  render() {
    return (
      <>
        <h2>todolist</h2>
        <Form onGetItem={this.getItem} />
        <List
          list={this.state.list}
          onRemove={this.remove}
          onChangeCheck={this.changeCheck}
        />
        <button onClick={this.removeAll}>批量删除</button>
        <button onClick={this.checkAll}>
          {this.state.flag ? "反选" : "全选"}
        </button>
      </>
    );
  }
}

export default App;
